package com.hjj.springboot.util;

import com.hjj.springboot.entity.HealthPlan;
import com.hjj.springboot.entity.UserHealthInfo;


import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

public class CalorieCalculator {

    // 计算基础代谢率
    private static double calculateBMR(UserHealthInfo user) {
        if (user.getSex().equals("男")) { // 男性
            return 88.362 + (13.397 * user.getWeight())
                    + (4.799 * user.getHeight()) - (5.677 * user.getAge());
        } else { // 女性
            return 447.593 + (9.247 * user.getWeight())
                    + (3.098 * user.getHeight()) - (4.330 * user.getAge());
        }
    }

    // 计算每日卡路里调整
    private static double calculateCalorieAdjustment(HealthPlan plan){
        double caloriesPerKg = getCaloriesPerKg(plan.getGoal());
        long days = calculateDays(plan);
        return plan.getQuantity() * caloriesPerKg / days;
    }

    // 总每日能量消耗
    private static double calculateTDEE(UserHealthInfo user) {
        return calculateBMR(user) * getActivityFactor(user.getActivity());
    }

    // 计算每日所需热量
    public static int calculatePlanCalories(UserHealthInfo user , HealthPlan plan) {
        return (int) Math.round(calculateTDEE(user) + calculateCalorieAdjustment(plan));
    }

    //    获取活动因子
    private static double getActivityFactor(String level) {
        switch (level) {
            case "久坐(很少运动)": return 1.2;  // 久坐
            case "轻度活动(每周1-3天运动)": return 1.375; // 轻度
            case "中度活动(每周4-6天运动)": return 1.55;  // 中度
            case "高度活动(每天运动)": return 1.725; // 活跃
            case "运动员级(每天高强度运动)": return 1.9;   // 非常活跃
            default: return 1.2;
        }
    }

    // 获取目标调整卡路里
    private static double getCaloriesPerKg(String goal) {
        switch (goal) {
            case "减脂": return -7700;
            case "增肌": return 5500;
            default: return 0;
        }
    }

    // 计算计划天数
    private static long calculateDays(HealthPlan plan) {
        LocalDate start = plan.getStartDate().toInstant()
                .atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate end = plan.getEndDate().toInstant()
                .atZone(ZoneId.systemDefault()).toLocalDate();
        long days = ChronoUnit.DAYS.between(start, end) + 1;
        return Math.max(days, 1); // 至少1天
    }

}
